package component.fy.com.common_module.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.sharesdk.onekeyshare.OnekeyShare;
import component.fy.com.common_module.R;
import component.fy.com.common_module.constant.AppConstant;
import component.fy.com.common_module.inter.PermissionListener;
import component.fy.com.common_module.utils.AndroidBug5497Workaround;
import component.fy.com.common_module.utils.WeiboDialogUtils;

/**
 * Created by Administrator on 2017/5/11 0011.
 */

public abstract class BaseFragment extends Fragment {
    //获取布局文件ID
    protected abstract int getLayoutId();

    protected BaseActivity mActivity;

    //布局加载
    protected abstract void initView(View view);

    //监听事件
    protected abstract void initEvents();

    //数据
    protected abstract void initData();

    private boolean isVisible = false;//当前Fragment是否可见
    private boolean isInitView = false;//是否与View建立起映射关系
    private boolean isFirstLoad = true;//是否是第一次加载数据

    private Unbinder unbinder;//ButterKnife在fragment中的使用
    /**
     * 权限监听接口
     */
    private static PermissionListener perListener;
    private Dialog loadingDialog;//加载数据框

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setRetainInstance(true);
        View view = inflater.inflate(getLayoutId(), container, false);
        AndroidBug5497Workaround.assistActivity(mActivity);//解决键盘冲突的方法
        unbinder = ButterKnife.bind(this, view);
        initView(view);
        initEvents();
        isInitView = true;
        lazyLoadData();
        return view;
    }

    /**
     * 请求权限
     *
     * @param permissions
     * @param listener
     */
    public void requestRunPermission(String[] permissions, PermissionListener listener) {
        Activity topActivity = ((BaseCommonApp) getActivity().getApplication()).getActivityManager().currentVisibleActivity();
        if (topActivity == null) {
            return;
        }
        perListener = listener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(topActivity, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            //未获取
            ActivityCompat.requestPermissions(topActivity, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            //获取了
            perListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    List<String> deniedList = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int grantResult = grantResults[i];
                        String permission = permissions[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            deniedList.add(permission);
                        }
                    }

                    if (deniedList.isEmpty()) {
                        perListener.onGranted();
                    } else {
                        perListener.onDenied(deniedList);
                    }
                }
                break;
        }
    }

    private ImageView imgBack, imgRight;
    private TextView tvTitle;
    private RelativeLayout layoutToolBar, rightLayout;
    private TextView rightLayoutTv;
    private ImageView rightLayoutImg;

    /**
     * 设置ToolBar背景色
     *
     * @param resId
     */
    protected void setToolBarBackground(View view, int resId) {
        layoutToolBar = (RelativeLayout) view.findViewById(R.id.common_toolbar_layout);
        layoutToolBar.setBackgroundResource(resId);
    }

    /**
     * 获取ToolBar返回键
     *
     * @return
     */
    protected ImageView getToolBarBack(View view) {
        imgBack = (ImageView) view.findViewById(R.id.common_toolbar_back);
        imgBack.setVisibility(View.VISIBLE);
        return imgBack;
    }

    /**
     * 设置ToolBar返回键
     *
     * @return
     */
    protected ImageView setToolBarBack(View view, int resId) {
        imgBack = (ImageView) view.findViewById(R.id.common_toolbar_back);
        imgBack.setVisibility(View.VISIBLE);
        imgBack.setBackgroundResource(resId);
        return imgBack;
    }

    /**
     * 设置ToolBar标题
     *
     * @param title
     */
    protected void setToolBarTitle(View view, String title) {
        tvTitle = (TextView) view.findViewById(R.id.common_toolbar_title);
        tvTitle.setText(title);
    }

    /**
     * 设置ToolBar标题及标题颜色
     *
     * @param title
     */
    protected void setToolBarTitle(View view, String title, int color) {
        tvTitle = (TextView) view.findViewById(R.id.common_toolbar_title);
        tvTitle.setText(title);
        tvTitle.setTextColor(mActivity.getResources().getColor(color));
    }

    /**
     * 设置ToolBar标题及标题颜色、字体大小
     *
     * @param title
     */
    protected void setToolBarTitle(View view, String title, int color, int size) {
        tvTitle = (TextView) view.findViewById(R.id.common_toolbar_title);
        tvTitle.setText(title);
        tvTitle.setTextColor(mActivity.getResources().getColor(color));
        tvTitle.setTextSize(size);
    }

    /**
     * 设置ToolBar右边图片
     *
     * @param resId
     * @return
     */
    protected ImageView setToolBarRightImg(View view, int resId) {
        imgRight = (ImageView) view.findViewById(R.id.common_toolbar_right_img);
        imgRight.setVisibility(View.VISIBLE);
        if (resId != 0) {
            imgRight.setImageResource(resId);
        }
        return imgRight;
    }

    /**
     * 获取ToolBar右边图片
     *
     * @return
     */
    protected ImageView getToolBarRightImg(View view) {
        imgRight = (ImageView) view.findViewById(R.id.common_toolbar_right_img);
        imgRight.setVisibility(View.VISIBLE);
        return imgRight;
    }

    /**
     * 设置并显示右边布局
     *
     * @param tvStr
     * @return
     */
    protected RelativeLayout setToolBarRightLayout(View view, String tvStr) {
        rightLayout = (RelativeLayout) view.findViewById(R.id.common_toolbar_right_layout);
        rightLayoutTv = (TextView) view.findViewById(R.id.common_toolbar_right_layout_tv);
        rightLayoutImg = (ImageView) view.findViewById(R.id.common_toolbar_right_layout_img);
        rightLayout.setVisibility(View.VISIBLE);
        rightLayoutTv.setText(tvStr);
        rightLayoutImg.setSelected(false);
        return rightLayout;
    }

    /**
     * 改变右边布局箭头状态
     */
    protected ImageView getToolBarRightLayoutImg() {
        return rightLayoutImg;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (BaseActivity) context;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            isVisible = true;
            lazyLoadData();
        } else {
            isVisible = false;
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    private void lazyLoadData() {
        if (isFirstLoad) {
//            LogUtil.m("第一次加载 " + " isInitView  " + isInitView + "  isVisible  " + isVisible + "   " + this.getClass().getSimpleName());
        } else {
//            LogUtil.m("不是第一次加载" + " isInitView  " + isInitView + "  isVisible  " + isVisible + "   " + this.getClass().getSimpleName());
        }
        if (!isFirstLoad || !isVisible || !isInitView) {
//            LogUtil.m("不加载" + "   " + this.getClass().getSimpleName());
            return;
        }
        initData();
        isFirstLoad = false;
    }

    /**
     * activity跳转不带数据
     *
     * @param from
     * @param to
     */
    protected void goToPage(Context from, Class<? extends BaseActivity> to) {
        Intent i = new Intent();
        i.setClass(from, to);
        from.startActivity(i);
    }

    /**
     * activity跳转
     *
     * @param from
     * @param to
     * @param data 携带数据
     */
    protected void goToPage(Context from, Class<? extends BaseActivity> to, Bundle data) {
        Intent i = new Intent();
        i.setClass(from, to);
        if (data != null) {
            i.putExtras(data);
        }
        from.startActivity(i);
    }

    /**
     * 显示加载框，带参数
     */
    protected void showLoading(String hint) {
//        LogUtil.e("显示加载框", "执行");
        if (TextUtils.isEmpty(hint)) {
            loadingDialog = WeiboDialogUtils.createLoadingDialog(getActivity(), "数据加载中...");
        } else {
            loadingDialog = WeiboDialogUtils.createLoadingDialog(getActivity(), hint);
        }
    }

    /**
     * 关闭加载框
     */
    protected void closeLoading() {
//        LogUtil.e("取消加载框", "执行");
        WeiboDialogUtils.closeDialog(loadingDialog);
    }

    /**
     * 关闭软键盘
     */
    protected void closeKeyboard(Activity context) {
        View view = context.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 清空集合
     *
     * @param list
     */
    protected void clearList(List... list) {
        for (List li : list) {
            if (li != null) {
                li.clear();
                li = null;
            }
        }
    }

    /**
     * 三方分享
     */
    protected void showShare() {
        Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.ic_launcher);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle("饭碗易购");
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl(AppConstant.Share_Url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText("饭碗易购");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        oks.setImageData(bitmap);
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl(AppConstant.Share_Url);
        // comment是我对这条分享的评论，仅在人人网使用
        oks.setComment("");
        // 启动分享GUI
        oks.show(mActivity);
    }

    /**
     * 销毁关闭当前activity
     */
    protected void finishCurrentActivity() {
        BaseCommonApp.getBaseApp().getActivityManager().finishActivity();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();//解除ButterKnife的绑定
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("STATE_SAVE_IS_HIDDEN", isHidden());
    }
}
